package com.ocom.ugcapi.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.WxServiceUrl;
import com.ocom.common.entity.human.EntityBizLeaveApply;
import com.ocom.common.entity.master.EntityMngUserInfo;
import com.ocom.common.enums.ApplyTypeEnum;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.activiti.ApplySaveRequest;
import com.ocom.common.request.activiti.ProcessInfoRequest;
import com.ocom.common.request.company.GetFlowkeyByPidRequest;
import com.ocom.common.request.ugcapi.GzhAddLeaveApply;
import com.ocom.common.request.ugcapi.GzhUserLeaveList;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.PageListResult;
import com.ocom.common.vo.activiti.SearchFlowVo;
import com.ocom.common.vo.company.FlowConfigVo;
import com.ocom.common.vo.human.XfUserInfoVo;
import com.ocom.ugcapi.client.ActivitiClientService;
import com.ocom.ugcapi.client.CompanyClientService;
import com.ocom.ugcapi.client.HumanClientService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@RestController
public class LdLeaveApplyController {

    @Autowired
    HumanClientService humanClientService;

    @Autowired
    ActivitiClientService activitiClientService;

    @Autowired
    CompanyClientService companyClientService;

    private final String leaveKey  = "leave-apply";



    // 新增审批
    @PostMapping(WxServiceUrl.Url_newLeaveApply)
    public Result ldLeaveApply(@RequestBody Map<String,Object> map){

        GzhAddLeaveApply request =JSON.parseObject(JSON.toJSONString(map),GzhAddLeaveApply.class);

        EntityBizLeaveApply entityBizLeaveApply = (EntityBizLeaveApply) request;

        entityBizLeaveApply.setComId(request.getUserInfo().getComId());
        entityBizLeaveApply.setPId(request.getUserInfo().getPId());

        Result<XfUserInfoVo> xfUser = humanClientService.getXfUserInfo(entityBizLeaveApply.getComId(),entityBizLeaveApply.getPId());
        if(xfUser.getCode()!=200 || xfUser.getData()==null){
            return xfUser;
        }
        Long deptId  =  xfUser.getData().getDeptId();
        if(deptId==null || deptId==0l){
            return ResultUtil.error(ResultEnum.Err_2045);
        }

        entityBizLeaveApply.setTitle(xfUser.getData().getPName()+"("+xfUser.getData().getDeptName() +")提交的"+ ApplyTypeEnum.getName(entityBizLeaveApply.getType()));

        ApplySaveRequest applySaveRequest=new ApplySaveRequest();
        applySaveRequest.setApplyKey(leaveKey+"-"+entityBizLeaveApply.getComId());
        applySaveRequest.setApplyUser(entityBizLeaveApply.getComId()+":"+entityBizLeaveApply.getPId());
        applySaveRequest.setReason(entityBizLeaveApply.getReason());
        applySaveRequest.getParams().put("days",entityBizLeaveApply.getDays());
        applySaveRequest.getParams().put("type",entityBizLeaveApply.getType());

        //y因为人员有多个库  id可能冲突 需要加单位
        applySaveRequest.getVariables().put("assignee0",entityBizLeaveApply.getComId()+":"+entityBizLeaveApply.getPId());

        GetFlowkeyByPidRequest getFlowkeyByPidRequest = new GetFlowkeyByPidRequest();
        getFlowkeyByPidRequest.setComId(entityBizLeaveApply.getComId());
        getFlowkeyByPidRequest.setPId(entityBizLeaveApply.getPId().intValue());
        getFlowkeyByPidRequest.setFlowCode(leaveKey);
        Result<FlowConfigVo> result3 = companyClientService.getFlowkeyByPid(getFlowkeyByPidRequest);

        if (result3.getCode() != 200) {
            return result3;
        }

        applySaveRequest.getVariables().putAll(result3.getData().getVariables());
        applySaveRequest.setApplyKey(leaveKey + "-" + entityBizLeaveApply.getComId());

        entityBizLeaveApply.setDefKey(leaveKey + "-" + entityBizLeaveApply.getComId());
        Result result = companyClientService.addLeavelApply(entityBizLeaveApply);
        if (result.getCode() != 200) return result;
        EntityBizLeaveApply entityBizLeaveApply1 = JSON.parseObject(JSON.toJSONString(result.getData()), EntityBizLeaveApply.class);

        //查部门的管理员  TODO

        applySaveRequest.setApplyId(entityBizLeaveApply1.getComId()+":"+entityBizLeaveApply1.getId());

        log.info("审批参数 【{}】",applySaveRequest);

        Result<Map<String,Object>> result1 = activitiClientService.submitApply(applySaveRequest);
//        System.out.println(result1);
//        System.out.println(applySaveRequest);


        if(result1.getCode()!=200){
            return result1;
        }

        EntityBizLeaveApply entityBizLeaveApply2 =new EntityBizLeaveApply();
        entityBizLeaveApply2.setComId(entityBizLeaveApply.getComId());
        entityBizLeaveApply2.setId(entityBizLeaveApply1.getId());
        entityBizLeaveApply2.setActivitiKey((String)result1.getData().get("processInstanceId"));
        companyClientService.updateLeavelApply(entityBizLeaveApply2);

        return ResultUtil.success();
    }


    // 列表
    @PostMapping(WxServiceUrl.Url_leaveApplyList)
    public Result leaveApplyList(@RequestBody Map<String,Object> map ){
        GzhUserLeaveList gzhUserLeaveList  =JSON.parseObject(JSON.toJSONString(map),GzhUserLeaveList.class);

        gzhUserLeaveList.setComId(gzhUserLeaveList.getUserInfo().getComId());
        gzhUserLeaveList.setPId(gzhUserLeaveList.getUserInfo().getPId());
        gzhUserLeaveList.setDefKey(leaveKey+"-"+gzhUserLeaveList.getComId());
        return  companyClientService.leavelApplyList(gzhUserLeaveList);
    }


    // 取消
    @PostMapping(WxServiceUrl.Url_cancelApply)
    public Result cancelApply(@RequestBody Map<String,Object> map){
        GzhAddLeaveApply request   =JSON.parseObject(JSON.toJSONString(map),GzhAddLeaveApply.class);
        EntityBizLeaveApply entityBizLeaveApply = (EntityBizLeaveApply) request;
        entityBizLeaveApply.setComId(request.getUserInfo().getComId());
        entityBizLeaveApply.setPId(request.getUserInfo().getPId());

        String key =leaveKey +"-"+entityBizLeaveApply.getComId();

        Result result1 = activitiClientService.cancelApply(key,key+":"+entityBizLeaveApply.getComId()+":"+entityBizLeaveApply.getId());
        if(result1.getCode()!=200){
            return result1;
        }
        entityBizLeaveApply.setStatus(3);
        return companyClientService.updateLeavelApply(entityBizLeaveApply);
    }



    // 详情
    @PostMapping(WxServiceUrl.Url_leaveApplyDeatil)
    public Result leaveApplyDeatil(@RequestBody Map<String,Object> map){
        ProcessInfoRequest request   =JSON.parseObject(JSON.toJSONString(map),ProcessInfoRequest.class);
        request.setComId(request.getUserInfo().getComId());
        request.setPId(request.getUserInfo().getPId());

        String key =leaveKey +"-"+request.getComId();



        EntityBizLeaveApply entityBizLeaveApply =new EntityBizLeaveApply();
        entityBizLeaveApply.setId(request.getId().longValue());
        entityBizLeaveApply.setComId(request.getComId());
        Result<EntityBizLeaveApply> leaveApplyResult = companyClientService.leavelApplyOne(entityBizLeaveApply);

        Result<List<SearchFlowVo>> result1 = activitiClientService.getProcessInfo(leaveApplyResult.getData().getActivitiKey(),key+":"+request.getComId()+":"+request.getId());
        if(result1.getCode()!=200){
            return result1;
        }

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("comId",request.getComId());
        jsonObject.put("status",0);
        jsonObject.put("page",1);
        jsonObject.put("size",500);
        //管理员
        Result<PageListResult<EntityMngUserInfo>>  mngUserList = companyClientService.getMngUserInfo(jsonObject);

        //list转map
        Map<String, String> stringMap = mngUserList.getData().getList().stream().collect(Collectors.toMap(e -> e.getId().toString(),
                e -> e.getUserName(),
                (e1, e2) -> e1));

        for (int i = 0; i < result1.getData().size(); i++) {
            SearchFlowVo searchFlowVo = result1.getData().get(i);
            if(null!=searchFlowVo.getUserId()){
                if(!searchFlowVo.getUserId().contains(":")){
                    if(stringMap.containsKey(searchFlowVo.getUserId())){
                        searchFlowVo.setUserId(stringMap.get(searchFlowVo.getUserId()));
                    }
                }else{
                    searchFlowVo.setUserId("发起人");
                }
            }
            if(searchFlowVo.getApprovalUser().size()>0){
                for (int j = 0; j < searchFlowVo.getApprovalUser().size(); j++) {
                    String uid = searchFlowVo.getApprovalUser().get(j);
                    if(stringMap.containsKey(uid)){
                        searchFlowVo.getApprovalUser().set(j,stringMap.get(uid));
                    }
                }
            }
            result1.getData().set(i,searchFlowVo);
        }
        return ResultUtil.success(result1.getData());
    }




}
